# -*-encoding: utf-8 -*-

from pyramid.view import view_config
from pyramid.view import view_defaults
from pyramid.response import Response
from pyramid.httpexceptions import HTTPFound
import json
from ..utils.Hash.HashUtil import HashUtil
from ..utils.Image.ImageUtil import ImageUtil
from ..utils.DB.MySQL import MySqlCRUD
from ..utils.DB.MySQL.InitSqlalchemy import db_session
import time, os, uuid, shutil, hashlib
import base64
from ..utils.Queue import UploadTasks
from ..utils.SMS import MobSMS
from ..utils.Cache.TokenCache import TokenCache
from ..utils.Cache.ChecksumCache import ChecksumCache
from ..utils.Models.Models import BgImg
import logging
from datetime import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
log = logging.getLogger(__name__)

from WebBase import Base

class ItemOperation(Base):

    @view_config(route_name='AppWebItemEditIndexRoute', renderer='../../templates/AppWebItemEdit.pt')
    def AppWebItemEditIndexRoute(self):
        md5, tel, username, email, type, portrait, csc, tString, eString, tokenString = '', '', '', '', '', '', '', '', '', ''
        try:
            tel = self.request.session['tel']
            md5 = self.request.params['md5']
            username = self.request.session['username']
            email = self.request.session['email']
            type = self.request.session['type']
            portrait = self.request.session['portrait'].replace('/media', '/static')
            tString = self.request.session['tString']
            eString = self.request.session['eString']
            tokenString = self.request.session['tokenString']
        except:
            return HTTPFound(location='/')
        tmpTokenString = self.calculateToken(tString, tel)
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return HTTPFound(location='/')
        sql = "select name, category, size, material, weight, price, aperture, url, description, path from material_info where md5 = %s"
        result = MySqlCRUD.selectImpl(sql, md5)
        size = result[0]['size'].split('*')
        map_size = {'size_x': size[0], 'size_y': size[1], 'size_z': size[2]}
        map = {'tel': tel, 'username': username, 'email': email, 'type': type, 'portrait': portrait, 'md5': md5}
        map.update(result[0])
        map.update(map_size)
        map.pop('size')
        map['path'] = map['path'].replace('/media', '/static')
        log.debug(map)
        return map

    #修改背景图
    @view_config(route_name='AppWebBgImgEditIndexRoute', renderer='../../templates/AppWebBgImgEdit.pt')
    def AppWebBgImgEditIndexRoute(self):
        md5, tel, username, email, type, portrait, csc, tString, eString, tokenString = '', '', '', '', '', '', '', '', '', ''
        try:
            tel = self.request.session['tel']
            md5 = self.request.params['md5']
            username = self.request.session['username']
            email = self.request.session['email']
            type = self.request.session['type']
            portrait = self.request.session['portrait'].replace('/media', '/static')
            tString = self.request.session['tString']
            eString = self.request.session['eString']
            tokenString = self.request.session['tokenString']
        except:
            return HTTPFound(location='/')
        tmpTokenString = self.calculateToken(tString, tel)
        if (eString <> HashUtil.getStringMD5(tel + tString)) or (tokenString <> tmpTokenString):
            map = {'RetCode': '114', 'message': '登录流程验证失败!', 'data': '重新登录'}
            cache.deleteCache(tel)
            jsonStr = json.dumps(map, ensure_ascii=False)
            log.error(jsonStr)
            return HTTPFound(location='/')
        sql = "select * from bgimage where md5 = %s"
        result = MySqlCRUD.selectImpl(sql, md5)
        map = {'tel': tel, 'username': username, 'email': email, 'type': type, 'portrait': portrait, 'md5': md5}
        map['path'] = result[0]['path'].replace('/media', '/static')
        map['description'] = result[0]['description']
        map['name'] = result[0]['name']
        map['price'] = result[0]['price']
        log.debug(map)
        return map

    @view_config(route_name='AppWebItemEditRoute', request_method='POST')
    def AppWebItemEditRoute(self):
        postParams =  self.request.POST
        log.debug(postParams)
        md5, category, name, material, size, weight, aperture, price, description, url ='', '', '', '', '', '', '', '', '', ''
        try:
            md5 = postParams.get('md5', '')
            category = postParams.get('category', '')
            name = postParams.get('name', '')
            material = postParams.get('material', '')
            size = postParams.get('size', '')
            weight = postParams.get('weight', '')
            aperture = postParams.get('aperture', '')
            price = postParams.get('price', '')
            description = postParams.get('description', '')
            url = postParams.get('url', '')

            log.debug('[AppWebItemEdit][md5]' + md5)
            log.debug('[AppWebItemEdit][category]' + category)
            log.debug('[AppWebItemEdit][name]' + name)
            log.debug('[AppWebItemEdit][material]' + material)
            log.debug('[AppWebItemEdit][size]' + size)
            log.debug('[AppWebItemEdit][weight]' + weight)
            log.debug('[AppWebItemEdit][aperture]' + aperture)
            log.debug('[AppWebItemEdit][price]' + price)
            log.debug('[AppWebItemEdit][description]' + description)
            log.debug('[AppWebItemEdit][url]' + url)

        except Exception, e:
            log.error(e)
        UploadTasks.updateMaterialInfoByQueue(md5, self.request.session['tel'], category, \
            name, material, size, weight, aperture, price, description, url)
        return Response("上传成功！")

    #背景图属性修改
    @view_config(route_name='AppWebBgImgEditRoute', request_method='POST')
    def AppWebBgImgEditRoute(self):
        postParams =  self.request.POST
        log.debug(postParams)
        try:
            md5 = postParams.get('current_md5', '')
            name = postParams.get('name', '')
            description = postParams.get('description', '')
            price = postParams.get('price', '')
            tel = self.request.session['tel']

        except Exception, e:
            log.error(e)
        bgimg = BgImg.query.filter(BgImg.MD5 == md5).one()
        bgimg.name = name
        bgimg.description = description
        bgimg.price = price
        db_session.commit()
        # updateSQL = '''UPDATE bgimage SET name = %s, description = %s WHERE MD5 = %s '''
        # resultImgUpdate = MySqlCRUD.updateImpl(updateSQL, name, description, md5)
        # log.debug('[SETUSERIMAGE][DONE] AFFECTED_ROW[' + str(resultImgUpdate) +']')

        return Response("上传成功！")

    @view_config(route_name='AppWebItemDeleteRoute', request_method='POST')
    def AppWebItemDeleteRoute(self):
        postParams =  self.request.POST
        log.debug(postParams)
        md5, tel ='', ''
        try:
            md5 = postParams.get('md5', '')
            tel = postParams.get('tel', '')

            log.debug('[AppWebItemEdit][md5]' + md5)
            log.debug('[AppWebItemEdit][tel]' + tel)
        except Exception, e:
            log.error(e)
        UploadTasks.deleteMaterialUserInfoByQueue(md5, tel)
        return Response("上传成功！")

    #背景图删除
    @view_config(route_name='AppWebBgImgDeleteRoute', request_method='POST')
    def AppWebBgImgDeleteRoute(self):
        postParams =  self.request.POST
        log.debug(postParams)
        md5, tel ='', ''
        try:
            md5 = postParams.get('md5', '')
            tel = postParams.get('tel', '')

            log.debug('[AppWebItemEdit][md5]' + md5)
            log.debug('[AppWebItemEdit][tel]' + tel)
        except Exception, e:
            log.error(e)
        deleteSQL = '''
            DELETE user_bgimage_info FROM user_bgimage_info
                INNER JOIN user_info
                ON user_bgimage_info.user_id = user_info.ID
                WHERE user_bgimage_info.MD5 = %s AND user_info.tel = %s;
        '''
        resultDelete = MySqlCRUD.deleteImpl(deleteSQL, md5, tel)
        log.debug('deleteMaterialUserInfoByQueue' + str(resultDelete))
        return Response("删除成功！")
